package com.dingding.order.core.grab.biz.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.code.BaseCodeMessage;
import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.model.push.PushModel;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.paravalidate.ValiResult;
import com.dingding.common.core.util.paravalidate.ValidateUtil;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.order.code.GrabOrderCodeMsg;
import com.dingding.order.core.enums.OrderEnums;
import com.dingding.order.core.grab.biz.IGrabOrderService;
import com.dingding.order.core.grab.dao.IUserGrabDao;
import com.dingding.order.dto.grab.ReqUserGrabDTO;
import com.dingding.order.dto.grab.ResUserGrabDTO;
import com.dingding.order.dto.grab.UserGrabPushDTO;
import com.dingding.order.dto.publish.PushData;

/**
 * 
* @ClassName: SpecialGrabOrderServiceImpl.java 
* @Package com.dingding.order.core.grab.biz.impl 
* @Description: TODO(用一句话描述该文件做什么) 
* @author hufan
* @date 2016年11月21日 下午7:43:05 
* @version V2.5.6
 */
@Component("specialGrabOrderService")
public class SpecialGrabOrderServiceImpl extends AbstractResponse<ResUserGrabDTO, ReqUserGrabDTO>  implements IGrabOrderService {

	
private Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name="userGrabDao")
	private IUserGrabDao userGrabDao;
	
	@Resource(name = "queueFacade")
	private IQueueFacade queueFacade;
	
	/**
	 * 
	 * @Title: userGrab 
	 * @Description: 用户抢单
	 * @param reqUserGrabDTO 用户抢单客户端请求Bean
	 * @author YHQ 
	 * @since V2.4.0
	 * @return ResponseEntity<ResUserGrabDTO>    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String userGrabOrder(String requestData) {
		
		// 出租车抢单，响应客户端Bean
		ResponseEntity<ResUserGrabDTO> response = new ResponseEntity<ResUserGrabDTO>();
		
		//专车抢单，客户端请求参数
		ReqUserGrabDTO reqUserGrabDTO = super.parseRequestJson(requestData);
		
		// 验证客户端请求参数
		if(!this.validateUserGrab(response, reqUserGrabDTO)) {
			return super.responseBeanToJson(response);
		}
		
		// 抢单操作
		boolean operationFlag = this.userGrabOperation(response, reqUserGrabDTO);
		
		// 抢单推送
		if(operationFlag){
			
			// 抢单推送
			this.grabPush(reqUserGrabDTO);
			
			// 抢单推送通知
			this.grabPushNotice(reqUserGrabDTO);
		}
		
		return super.responseBeanToJson(response);
	}
	
	/**
	 * 
	 * @Title: validateUserGrab 
	 * @Description: 验证用户抢单请求参数
	 * @param response 用户抢单响应Bean
	 * @param reqUserGrabDTO 用户抢单响应Bean
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return boolean    返回类型
	 * 
	 */
	public boolean validateUserGrab(ResponseEntity<ResUserGrabDTO> response,ReqUserGrabDTO reqUserGrabDTO){
		
		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqUserGrabDTO, ReqUserGrabDTO.class);

		if (!valiResult.isAvailable()) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setNullPropList(valiResult.getNullFieldList()); // 空字段名称
			response.setErrorMessage(BaseCodeMessage.DATA_NULL_PARAM_MESSAGE);
			response.setPromptMessage(BaseCodeMessage.HTTP_REQUEST_ERROR);
			log.error("为空字段为：" + valiResult.getNullFieldName());
			return false;
		}
		
		// 判断该用户是否存在未完成订单
		List<UserspecialorderT> userspecialorderts = userGrabDao.getUserSpecialOrdertList(reqUserGrabDTO.getUserId());
		
		if(userspecialorderts != null && userspecialorderts.size() > 0){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.EXISTS_NOT_COMPLETED_ORDER);// 您尚有未完成订单，请先完成！
			response.setPromptMessage(GrabOrderCodeMsg.EXISTS_NOT_COMPLETED_ORDER);
			log.error("有未完成订单，用户为：" + reqUserGrabDTO.getUserId());
			return false;
		}
		
		return true;
	}

	/**
	 * 
	 * @Title: userGrabOperation 
	 * @Description: 用户抢单操作
	 * @param reqUserGrabDTO 客户端请求参数
	 * @param response 用户抢单响应Bean
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean userGrabOperation(ResponseEntity<ResUserGrabDTO> response,ReqUserGrabDTO reqUserGrabDTO){
		
		ResUserGrabDTO resUserGrabDTO = new ResUserGrabDTO();
		
		// 根据订单获取订单信息
		UserspecialorderT userspecialorderT = userGrabDao.geUserspecialorderT(reqUserGrabDTO.getOid());
		
		// 判断当前订单是否存在
		if(userspecialorderT == null){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);// 客户端请求数据为空
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);// 客户端请求数据为空
			return false;
		}
		
		// 订单类型不是待指派订单
		if(userspecialorderT.getOrderStatus() != OrderEnums.STAY_ASSIGN.getIndex()){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_STATUS_ERROR);// 客户端请求数据为空
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_STATUS_ERROR);// 客户端请求数据为空
			return false;
		}
		
		// 抢单人
		userspecialorderT.setGrabOrderUserId(reqUserGrabDTO.getUserId());
		// 订单状态
		userspecialorderT.setOrderStatus(OrderEnums.STAY_ABOARD.getIndex());
		// 抢单时间或指派订单时间
		userspecialorderT.setAppointTime(new Date());
		
		// 订单状态
		resUserGrabDTO.setOrderStatus(userspecialorderT.getOrderStatus());
		
		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resUserGrabDTO);
		
		return true;
	}
	
	/**
	 * 
	 * @Title: grabPush 
	 * @Description: 抢单推送 
	 * @param reqUserGrabDTO 抢单时客户端请求参数
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return void    返回类型
	 * 
	 */
	@Transactional(readOnly = true)
	public void grabPush(ReqUserGrabDTO reqUserGrabDTO){
		
		UserGrabPushDTO userGrabPushDTO = userGrabDao.getUserGrabPushInfo(reqUserGrabDTO.getOid(), reqUserGrabDTO.getUserId());
		
		if(userGrabPushDTO != null){
			
			//设置司机的id
			userGrabPushDTO.setOtherUserId(reqUserGrabDTO.getUserId());
			
			// 推送Bean
			PushData pushData = new PushData();

			// 推送序号(时间戳)
			pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			pushData.setModular("assignOrderPush");
			pushData.setResponseBody(userGrabPushDTO);

			PushRequestDTO pushRequestDTO = new PushRequestDTO();

			// 推送别名
			pushRequestDTO.setAliasId(userGrabPushDTO.getAliasId());
			pushRequestDTO.setAlert("订单已被指派");

			// 设备类型
			if (userGrabPushDTO.getClientType().equals("Android")) {
				pushRequestDTO.setClientType(ClientType.Android);
			} else if (userGrabPushDTO.getClientType().equals("iOS")) {
				pushRequestDTO.setClientType(ClientType.iOS);
			}

			// 消息推送类型
			pushRequestDTO.setPushType(PushType.alert_msgcontent);

			// 推送类型
			pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));

			log.info("订单指派推送内容： "+JSONUtil.toJSONString(pushRequestDTO));
			queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
			
		}
		
	}
	
	/**
	 * 
	 * @Title: grabPushNotice 
	 * @Description: 抢单推送通知
	 * @param     设定文件 
	 * @author YHQ 
	 * @return void    返回类型
	 */
	public void grabPushNotice(ReqUserGrabDTO reqUserGrabDTO){
		
		UserGrabPushDTO userGrabPushDTO = userGrabDao.getUserGrabPushInfo(reqUserGrabDTO.getOid(), reqUserGrabDTO.getUserId());
		
		if(userGrabPushDTO != null){
			
			// 推送Bean
			PushData pushData = new PushData();
			
			String content = "司机已接单！";
			
			// 推送序号(时间戳)
			pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			pushData.setModular("newsNoticePush");
			// 确认到达推送内容
			pushData.setResponseBody(PushModel.noticeModel(1, content, null));
			
			PushRequestDTO pushRequestDTO = new PushRequestDTO();
			
			// 推送别名
			pushRequestDTO.setAliasId(userGrabPushDTO.getAliasId());
			
			// 设备类型
			if (userGrabPushDTO.getClientType().equals("Android")) {
				pushRequestDTO.setClientType(ClientType.Android);
			} else if (userGrabPushDTO.getClientType().equals("iOS")) {
				pushRequestDTO.setClientType(ClientType.iOS);
			}
			
			// 消息推送类型
			pushRequestDTO.setPushType(PushType.msgcontent);
			
			// 推送类型
			pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
			
			log.info("用户抢单通知内容：" + JSONUtil.toJSONString(pushRequestDTO));
			queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
		}
		
		
	}

	@Override
	public String driverGrabOrder(String requestData) {
		
		return null;
	}

}
